package com.example.templateapp.util

import android.text.InputFilter
import android.text.Spanned
import android.util.Log

class CashierInputFilter(point: Int = 2, var isAmount: Boolean = true) : InputFilter {

    private var mPointLength: Int = 2


    init {
        this.mPointLength = point
    }

    /**
     * @param source  新输入的字符串
     * @param start   新输入的字符串起始下标，一般为0
     * @param end    新输入的字符串终点下标，一般为source长度-1
     * @param dest   输入之前文本框内容
     * @param dstart  原内容起始坐标，一般为0
     * @param dend   原内容终点坐标，一般为dest长度-1
     * @return     输入内容
     */
    override fun filter(
        source: CharSequence,
        start: Int,
        end: Int,
        dest: Spanned,
        dstart: Int,
        dend: Int
    ): CharSequence {
        Log.d(
            "MoneyInputFilter",
            "[source:$source][start:$start][end:$end][dest:$dest][dstart:$dstart][dend:$dend]"
        )

        val start = dest.subSequence(0, dstart)
        val end = dest.subSequence(dend, dest.length)
        val target = start.toString() + source + end//字符串变化后的结果
        val backup = dest.subSequence(dstart, dend)//将要被替换的字符串

        if (target.indexOf(".") == 0) {//不允许第一个字符为.
            return backup
        }


        if (target.startsWith("0") && !target.startsWith("0.") && "0" != target) {//不允许出现0123、0456这类字符串
            return backup
        }

        //如果不是金额，只限制小数位数并小于1（即限制为折扣数）
        if (isAmount.not()) {
            if (target.startsWith("0").not()) return backup
            if (target.contains(".") && !target.startsWith("0.")) return backup
        }

        //限制小数点后面只能有两位小数
        val index = target.indexOf(".")
        if (index >= 0 && index + mPointLength + 2 <= target.length) {
            return backup
        }

        return source

    }
}